package com.hp.gxw.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hp.gxw.cache.CommonCache;
import com.hp.gxw.constant.DefaultValueConstant;
import com.hp.gxw.constant.LayTableR;
import com.hp.gxw.constant.QueryTypeConstant;
import com.hp.gxw.constant.R;
import com.hp.gxw.entity.BaseCommonConstant;
import com.hp.gxw.entity.BaseCommonDataDictionaryAndSet;
import com.hp.gxw.entity.BaseCommonQueryTable;
import com.hp.gxw.service.IBaseCommonConstantService;
import com.hp.gxw.service.IBaseCommonDataDictionaryAndSetService;
import com.hp.gxw.service.IBaseCommonQueryTableService;
import com.hp.gxw.utils.ConditionUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author huangping
 * @since 2023-03-22
 */
@Controller
@RequestMapping("/manage/common_data_dictionary_and_set")
public class CommonDataDictionaryAndSetController {

    @Autowired
    private IBaseCommonDataDictionaryAndSetService iBaseCommonDataDictionaryAndSetService;

    @Autowired
    private IBaseCommonQueryTableService iBaseCommonQueryTableService;

    @Autowired
    private IBaseCommonConstantService iBaseCommonConstantService;

    @Autowired
    private CommonCache commonCache;

    @GetMapping("/index")
    public String index(){
        return "common/table_set/index";
    }

    @GetMapping("/setHtml/{id}/{constantId}")
    public String set(@PathVariable("id") Long id, @PathVariable("constantId") Long constantId, Model model){
        List<BaseCommonConstant> list = iBaseCommonConstantService.list(new LambdaQueryWrapper<BaseCommonConstant>().ne(BaseCommonConstant::getId, constantId));
        BaseCommonDataDictionaryAndSet set = iBaseCommonDataDictionaryAndSetService.getById(id);
        List<BaseCommonQueryTable> tableList = iBaseCommonQueryTableService.list(new LambdaQueryWrapper<BaseCommonQueryTable>().eq(BaseCommonQueryTable::getDictionaryId, id));
        model.addAttribute("id", String.valueOf(id));
        model.addAttribute("queryConstantId", set.getQueryConstantId());
        model.addAttribute("associatedFiled", set.getAssociatedFiled());
        model.addAttribute("tableList", tableList);
        model.addAttribute("constantList", list);
        return "common/table_set/set";
    }

    @PostMapping("/constant_list")
    @ResponseBody
    public LayTableR constant_list(Integer page, Integer limit, String master) throws Exception {
        QueryWrapper<BaseCommonConstant> ew = ConditionUtil.convert(master, new QueryWrapper<BaseCommonConstant>());
        Page<BaseCommonConstant> pageList = iBaseCommonConstantService.page(new Page<BaseCommonConstant>(page, limit), ew);
        return LayTableR.result(0, pageList.getTotal(), pageList.getRecords());
    }

    @PostMapping("/field_list/{id}/{fieldId}")
    @ResponseBody
    public LayTableR field_list(@PathVariable("id") Long id, @PathVariable("fieldId") Long fieldId) throws Exception {
        List<BaseCommonDataDictionaryAndSet> list = iBaseCommonDataDictionaryAndSetService.list(new LambdaQueryWrapper<BaseCommonDataDictionaryAndSet>().eq(BaseCommonDataDictionaryAndSet::getConstantId, id));
        List<BaseCommonQueryTable> queryTables = iBaseCommonQueryTableService.list(new LambdaQueryWrapper<BaseCommonQueryTable>().eq(BaseCommonQueryTable::getDictionaryId, fieldId));
        List<Map> resultList = new ArrayList<>();
        for(BaseCommonDataDictionaryAndSet commonDataDictionaryAndSet : list){
            Map map = BeanUtils.describe(commonDataDictionaryAndSet);
            for(BaseCommonQueryTable commonQueryTable : queryTables){
                if(commonDataDictionaryAndSet.getTableField().equals(commonQueryTable.getQueryField())){
                    map.put("LAY_CHECKED", true);
                    break;
                }
            }
            resultList.add(map);
        }
        return LayTableR.result(0,resultList.size(),resultList);
    }

    @PostMapping("/table_field_list/{id}")
    @ResponseBody
    public Object table_field_list(@PathVariable("id") Long id){
        return iBaseCommonDataDictionaryAndSetService.getTableInfo(id);
    }

    @RequestMapping("/query_type_list")
    @ResponseBody
    public Object query_type_list(){
        List<Map<String,String>> list = new ArrayList<>();
        for(QueryTypeConstant constant : QueryTypeConstant.values()){
            Map<String,String> map = new HashMap<>();
            map.put("label",constant.getCode());
            map.put("value",constant.getCode());
            list.add(map);
        }
        return list;
    }

    @RequestMapping("/default_value_list")
    @ResponseBody
    public Object default_value_list(){
        List<Map<String,String>> list = new ArrayList<>();
        for(DefaultValueConstant constant : DefaultValueConstant.values()){
            Map<String,String> map = new HashMap<>();
            map.put("label",constant.getCode());
            map.put("value",constant.getCode());
            list.add(map);
        }
        return list;
    }

    @PostMapping("/refresh")
    @ResponseBody
    public R refresh(Long id){
        try {
            iBaseCommonDataDictionaryAndSetService.refreshTableInfo(id);
        }catch (Exception e){
            e.printStackTrace();
            return R.error("系统异常");
        }
        return R.ok();
    }

    @PostMapping("/save_set")
    @ResponseBody
    public R save_set(String info){
        List<BaseCommonDataDictionaryAndSet> list = JSON.parseArray(info, BaseCommonDataDictionaryAndSet.class);
        try {
            iBaseCommonDataDictionaryAndSetService.updateBatchById(list);
        }catch (Exception e){
            e.printStackTrace();
            return R.error("系统异常");
        }
        BaseCommonConstant constant = iBaseCommonConstantService.getById(list.get(0).getConstantId());
        commonCache.removeByUrl(constant.getUrl());
        return R.ok();
    }

    @PostMapping("/save_query_table")
    @ResponseBody
    public R save_query_table(Long id, Long constantId, String associatedFiled, String fields){
        try {
            iBaseCommonDataDictionaryAndSetService.saveQueryTable(id,constantId,associatedFiled,fields);
        }catch (Exception e){
            e.printStackTrace();
            return R.error("系统异常");
        }
        return R.ok();
    }
}

